import Toast from '/tdesign-miniprogram/toast/index';
import {
  fetchSettleDetail
} from '../../../services/order/orderConfirm';
import {
  commitPay,
  wechatPayOrder
} from './pay';
import {
  getAddressPromise
} from '../../usercenter/address/list/util';
import {
  users
} from '../../../tools/users'
import {
  ds
} from '../../../tools/data'
import {
  dsx
} from '../../../tools/datax'
import {
  shops
} from '../../../tools/shops'
import {
  ui
} from '../../../tools/ui'
import {
  msg
} from '../../../tools/msg'
import {
  adv
} from '../../../tools/adv';
import {
  nav2
} from '~/tools/nav2';

const stripeImg = `/static/img/stripe.png`;

Page({
  data: {
    user: null,
    placeholder: '备注信息',
    stripeImg,
    loading: false,
    settleDetailData: {
      storeGoodsList: [], //正常下单商品列表
      outOfStockGoodsList: [], //库存不足商品
      abnormalDeliveryGoodsList: [], // 不能正常配送商品
      inValidGoodsList: [], // 失效或者库存不足
      limitGoodsList: [], //限购商品
      couponList: [], //门店优惠券信息
    }, // 获取结算页详情 data
    orderCardList: [], // 仅用于商品卡片展示
    couponsShow: false, // 显示优惠券的弹框
    invoiceData: {
      email: '', // 发票发送邮箱
      buyerTaxNo: '', // 税号
      invoiceType: null, // 开票类型  1：增值税专用发票； 2：增值税普通发票； 3：增值税电子发票；4：增值税卷式发票；5：区块链电子发票。
      buyerPhone: '', //手机号
      buyerName: '', //个人或公司名称
      titleType: '', // 发票抬头 1-公司 2-个人
      contentType: '', //发票内容 1-明细 2-类别
    },
    goodsRequestList: [],
    userAddressReq: null,
    popupShow: false, // 不在配送范围 失效 库存不足 商品展示弹框
    notesPosition: 'center',
    storeInfoList: [],
    storeNoteIndex: 0, //当前填写备注门店index
    promotionGoodsList: [], //当前门店商品列表(优惠券)
    couponList: [], //当前门店所选优惠券
    submitCouponList: [], //所有门店所选优惠券
    currentStoreId: null, //当前优惠券storeId
    userAddress: null,
    submitDisabled: true,
  },
  payLock: false,
  noteInfo: [],
  tempNoteInfo: [],

  onLoad(options) {
    const {
      ticketOrder,
      ticket
    } = options
    this.setData({
      loading: true,
      ticketOrder,
      ticket: ticketOrder ? JSON.parse(ticket) : null
    });
    // console.log('ticketOrder', ticketOrder)
    // console.log('ticket', this.data.ticket)

    this.loadAddr(options)
    this.loadUser()
  },
  loadAddr(options) {
    const that = this
    ds.cloudGetByOpenid('delivery_addr', res => {
      // console.log(res)
      const addr = res.result.data[0] || null
      if (addr) {
        this.makeUserAddress(addr)
      }
      that.handleOptionsParams(options);
    })
  },
  makeUserAddress(addr) {
    const userAddress = {
      detailAddress: addr.name + ', ' + addr.mobile + ', ' + addr.locText + ', ' + addr.locHome
    }
    this.setData({
      userAddress,
      addr
    })
    return userAddress
  },
  loadUser() {
    users.getUserInfo()
      .then(info => {
        this.setData({
          user: info
        })
        if (info) this.enableSubmit(true)
      })
  },

  onShow() {
    // const invoiceData = wx.getStorageSync('invoiceData');
    // if (invoiceData) {
    //   //处理发票
    //   this.invoiceData = invoiceData;
    //   this.setData({
    //     invoiceData,
    //   });
    //   wx.removeStorageSync('invoiceData');
    // }
  },
  init() {
    this.setData({
      loading: true,
    });
    const {
      goodsRequestList
    } = this;
    this.handleOptionsParams({
      goodsRequestList
    });
  },
  // 处理不同情况下跳转到结算页时需要的参数
  handleOptionsParams(options, couponList) {
    let {
      goodsRequestList
    } = this; // 商品列表
    let {
      userAddressReq
    } = this; // 收货地址
    // vipPrice
    const {
      vipPrice
    } = options
    if (vipPrice) {
      this.setData({
        vipPrice
      })
    }
    const storeInfoList = []; // 门店列表
    // 如果是从地址选择页面返回，则使用地址显选择页面新选择的地址去获取结算数据
    if (options.userAddressReq) {
      userAddressReq = options.userAddressReq;
    }
    if (options.type === 'cart') {
      // 从购物车跳转过来时，获取传入的商品列表数据
      const goodsRequestListJson = wx.getStorageSync('order.goodsRequestList');
      goodsRequestList = JSON.parse(goodsRequestListJson);
      // console.log(goodsRequestList)
    } else if (typeof options.goodsRequestList === 'string') {
      goodsRequestList = JSON.parse(options.goodsRequestList);
    }

    //获取结算页请求数据列表
    const storeMap = {};
    goodsRequestList.forEach((goods) => {
      if (!storeMap[goods.storeId]) {
        storeInfoList.push({
          storeId: goods.storeId,
          storeName: goods.storeName,
          fastDelivery: goods.fastDelivery
        });
        storeMap[goods.storeId] = true;
      }
    });
    this.goodsRequestList = goodsRequestList;
    this.storeInfoList = storeInfoList;
    const params = {
      goodsRequestList,
      storeInfoList,
      userAddressReq,
      couponList,
    };
    fetchSettleDetail(params).then(
      (res) => {
        this.setData({
          loading: false,
        });
        // console.log(res.data)
        this.settleDetail = res.data
        this.initData();
      },
      () => {
        //接口异常处理
        this.handleError();
      },
    );
  },
  // 数据准备
  initData() {
    const settleDetail = this.settleDetail
    // 转换商品卡片显示数据
    const data = this.handleResToGoodsCard(settleDetail);
    this.userAddressReq = settleDetail.userAddress;
    if (settleDetail.userAddress) {
      this.setData({
        userAddress: settleDetail.userAddress
      });
    }

    // 商品总数
    let amount = 0
    data.storeGoodsList[0].skuDetailVos.forEach(ele => {
      amount += ele.quantity
    })
    data.totalGoodsCount = amount

    // 处理地址相关
    if (this.data.userAddress) {
      // console.log(data)
      const addr = this.data.addr
      data.totalDeliveryFee = addr.stepFee * amount
      data.storeGoodsList[0].storeId = addr.shop
      data.storeGoodsList[0].storeName = shops.getShop(addr.shop).name
    }
    data.totalPromotionAmount = 0
    data.totalPayAmount = (data.totalSalePrice * 1 + data.totalDeliveryFee * 1).toFixed(2)
    data.totalSalePrice = (data.totalSalePrice * 1).toFixed(2)
    data.settleType = 1

    // 水票满赠
    if (this.data.ticketOrder) {
      const ticket = this.data.ticket
      const gift = Math.floor(amount / ticket.unit) * ticket.gift
      // console.log('gift', gift)
      this.setData({
        gift,
        amount
      })
    }

    this.setData({
      settleDetailData: data
    });
    // console.log(data)
    this.isInvalidOrder(data);
  },
  async setupFastDelivery() {
    const {
      addr,
      settleDetailData
    } = this.data
    // console.log(this.data)
    const goods = settleDetailData.storeGoodsList[0].skuDetailVos[0]
    if (!goods.fastDelivery) return true

    // time
    const now = new Date();
    const currentHour = now.getHours();
    if (currentHour < 9 || currentHour >= 19) {
      await ui.confirmx('不在配送时间内。明天再来吧~')
      return false
    }

    // distance
    if (!addr.distance) {
      const ok = await ui.confirmx('请重新编辑地址以估算距离。是否去编辑？')
      if (ok) {
        wx.navigateTo({
          url: '/pages/delivery/manage',
        })
      }
      return false
    }

    if (addr.distance > 3) {
      const ok = await ui.confirmx(`当前地址${addr.distance.toFixed(2)}公里，超出配送范围。是否使用新的地址？`)
      if (ok) {
        wx.navigateTo({
          url: '/pages/delivery/manage',
        })
      }
      return false
    }

    return true
  },
  isInvalidOrder(data) {
    // 失效 不在配送范围 限购的商品 提示弹窗
    if (
      (data.limitGoodsList && data.limitGoodsList.length > 0) ||
      (data.abnormalDeliveryGoodsList &&
        data.abnormalDeliveryGoodsList.length > 0) ||
      (data.inValidGoodsList && data.inValidGoodsList.length > 0)
    ) {
      this.setData({
        popupShow: true
      });
      return true;
    }
    this.setData({
      popupShow: false
    });
    if (data.settleType === 0) {
      return true;
    }
    return false;
  },

  handleError() {
    Toast({
      context: this,
      selector: '#t-toast',
      message: '结算异常, 请稍后重试',
      duration: 2000,
      icon: '',
    });

    setTimeout(() => {
      wx.navigateBack();
    }, 1500);
    this.setData({
      loading: false,
    });
  },
  getRequestGoodsList(storeGoodsList) {
    const filterStoreGoodsList = [];
    storeGoodsList &&
      storeGoodsList.forEach((store) => {
        const {
          storeName
        } = store;
        store.skuDetailVos &&
          store.skuDetailVos.forEach((goods) => {
            const data = goods;
            data.storeName = storeName;
            filterStoreGoodsList.push(data);
          });
      });
    return filterStoreGoodsList;
  },
  handleGoodsRequest(goods, isOutStock = false) {
    const {
      reminderStock,
      quantity,
      storeId,
      uid,
      saasId,
      spuId,
      goodsName,
      skuId,
      storeName,
      roomId,
    } = goods;
    const resQuantity = isOutStock ? reminderStock : quantity;
    return {
      quantity: resQuantity,
      storeId,
      uid,
      saasId,
      spuId,
      goodsName,
      skuId,
      storeName,
      roomId,
    };
  },
  handleResToGoodsCard(data) {
    // 转换数据 符合 goods-card展示
    const orderCardList = []; // 订单卡片列表
    const storeInfoList = [];
    const submitCouponList = []; //使用优惠券列表;

    data.storeGoodsList &&
      data.storeGoodsList.forEach((ele) => {
        const orderCard = {
          id: ele.storeId,
          storeName: ele.storeName,
          status: 0,
          statusDesc: '',
          amount: ele.storeTotalPayAmount,
          goodsList: [],
        }; // 订单卡片
        ele.skuDetailVos.forEach((item, index) => {
          // console.log(item)
          orderCard.goodsList.push({
            id: index,
            thumb: item.image,
            title: item.goodsName,
            specs: item.skuSpecLst.map((s) => s.specValue), // 规格列表 string[]
            price: item.tagPrice || item.settlePrice || '0', // 优先取限时活动价
            settlePrice: item.settlePrice,
            titlePrefixTags: item.tagText ? [{
              text: item.tagText
            }] : [],
            num: item.quantity,
            skuId: item.skuId,
            spuId: item.spuId,
            storeId: item.storeId,
          });
        });

        storeInfoList.push({
          storeId: ele.storeId,
          storeName: ele.storeName,
          remark: '',
        });
        submitCouponList.push({
          storeId: ele.storeId,
          couponList: ele.couponList || [],
        });
        this.noteInfo?.push('');
        this.tempNoteInfo?.push('');
        orderCardList.push(orderCard);
      });

    this.setData({
      orderCardList,
      storeInfoList,
      submitCouponList
    });
    return data;
  },
  onGotoAddress() {
    wx.navigateTo({
      url: '/pages/delivery/manage',
    })
  },
  selAddrCallback(list, index) {
    const addr = list[index]
    this.makeUserAddress(addr)
    this.saveAddrInUse(addr)
    this.initData()
  },
  saveAddrInUse(addr) {
    ui.loading()
    const that = this
    const data2update = {
      ...addr
    }
    data2update.list = undefined
    dsx.cloudUpdateWhere('delivery_addr', {
      _openid: true
    }, {
      ...data2update
    }).then(res => {
      ui.loading(false)
      ui.toast(res.result.errMsg.endsWith(':ok'))
    })
  },
  _onGotoAddress() {
    /** 获取一个Promise */
    getAddressPromise()
      .then((address) => {
        this.handleOptionsParams({
          userAddressReq: {
            ...address,
            checked: true
          },
        });
      })
      .catch(() => {});

    const {
      userAddressReq
    } = this; // 收货地址

    let id = '';

    if (userAddressReq?.id) {
      id = `&id=${userAddressReq.id}`;
    }

    wx.navigateTo({
      url: `/pages/usercenter/address/list/index?selectMode=1&isOrderSure=1${id}`,
    });
  },
  onNotes(e) {
    const {
      storenoteindex: storeNoteIndex
    } = e.currentTarget.dataset;
    // 添加备注信息
    this.setData({
      dialogShow: true,
      storeNoteIndex,
    });
  },
  onInput(e) {
    const {
      storeNoteIndex
    } = this.data;
    this.noteInfo[storeNoteIndex] = e.detail.value;
  },
  onBlur() {
    this.setData({
      notesPosition: 'center',
    });
  },
  onFocus() {
    this.setData({
      notesPosition: 'self',
    });
  },
  onTap() {
    this.setData({
      placeholder: '',
    });
  },
  onNoteConfirm() {
    // 备注信息 确认按钮
    const {
      storeInfoList,
      storeNoteIndex
    } = this.data;
    this.tempNoteInfo[storeNoteIndex] = this.noteInfo[storeNoteIndex];
    storeInfoList[storeNoteIndex].remark = this.noteInfo[storeNoteIndex];

    this.setData({
      dialogShow: false,
      storeInfoList,
    });
  },
  onNoteCancel() {
    // 备注信息 取消按钮
    const {
      storeNoteIndex
    } = this.data;
    this.noteInfo[storeNoteIndex] = this.tempNoteInfo[storeNoteIndex];
    this.setData({
      dialogShow: false,
    });
  },

  onSureCommit() {
    // 商品库存不足继续结算
    const {
      settleDetailData
    } = this.data;
    const {
      outOfStockGoodsList,
      storeGoodsList,
      inValidGoodsList
    } =
    settleDetailData;
    if (
      (outOfStockGoodsList && outOfStockGoodsList.length > 0) ||
      (inValidGoodsList && storeGoodsList)
    ) {
      // 合并正常商品 和 库存 不足商品继续支付
      // 过滤不必要的参数
      const filterOutGoodsList = [];
      outOfStockGoodsList &&
        outOfStockGoodsList.forEach((outOfStockGoods) => {
          const {
            storeName
          } = outOfStockGoods;
          outOfStockGoods.unSettlementGoods.forEach((ele) => {
            const data = ele;
            data.quantity = ele.reminderStock;
            data.storeName = storeName;
            filterOutGoodsList.push(data);
          });
        });
      const filterStoreGoodsList = this.getRequestGoodsList(storeGoodsList);
      const goodsRequestList = filterOutGoodsList.concat(filterStoreGoodsList);
      this.handleOptionsParams({
        goodsRequestList
      });
    }
  },
  enableSubmit(enable) {
    this.setData({
      submitDisabled: !enable
    })
  },
  // 提交订单
  async submitOrder() {
    if (this.data.submitDisabled) return
    if (!await this.setupFastDelivery(this.data.storeGoodsList?.[0].skuDetailVos?.[0])) return
    if (!await ui.confirmx('确认提交吗？')) return

    const {
      settleDetailData,
      userAddressReq,
      invoiceData,
      storeInfoList,
      submitCouponList,
      userAddress
    } = this.data;
    const {
      goodsRequestList
    } = this;

    if (!userAddress.detailAddress) {
      ui.confirm('您填写地址，以便小哥及时配送！')
      return
    }

    if (
      this.payLock ||
      !settleDetailData.settleType ||
      !settleDetailData.totalAmount
    ) {
      return;
    }
    this.payLock = true;
    const resSubmitCouponList = this.handleCouponList(submitCouponList);
    const params = {
      userAddressReq: settleDetailData.userAddress || userAddressReq,
      goodsRequestList: goodsRequestList,
      userName: settleDetailData.userAddress?.name || userAddressReq?.name || 'unknown',
      totalAmount: settleDetailData.totalPayAmount, //取优惠后的结算金额
      invoiceRequest: null,
      storeInfoList,
      couponList: resSubmitCouponList,
      deductFeeInfo: settleDetailData.deductFeeInfo // 使用佣金结算
    };
    if (invoiceData && invoiceData.email) {
      params.invoiceRequest = invoiceData;
    }
    commitPay(params).then((res) => {
        this.payLock = false;
        const {
          data // data is useless but do not change this :(
        } = res;
        // console.log(settleDetailData)
        if (this.isInvalidOrder(data)) { // 提交出现 失效 不在配送范围 限购的商品 提示弹窗
          return;
        }
        if (res.code === 'Success') {
          this.enableSubmit(false)
          this.updateCoupon(settleDetailData.couponInfo?.list)
          this.handlePay(data, settleDetailData); // data is useless

          // clear cart
          const pages = getCurrentPages();
          const prevPage = pages[pages.length - 2];
          if (prevPage.clearSelection) prevPage.clearSelection()
        } else {
          Toast({
            context: this,
            selector: '#t-toast',
            message: res.msg || '提交订单超时，请稍后重试',
            duration: 2000,
            icon: '',
          });
          setTimeout(() => { // 提交支付失败   返回购物车            
            wx.navigateBack();
          }, 2000);
        }
      },
      (err) => {
        this.payLock = false;
        if (
          err.code === 'CONTAINS_INSUFFICIENT_GOODS' ||
          err.code === 'TOTAL_AMOUNT_DIFFERENT'
        ) {
          Toast({
            context: this,
            selector: '#t-toast',
            message: err.msg || '支付异常',
            duration: 2000,
            icon: '',
          });
          this.init();
        } else if (err.code === 'ORDER_PAY_FAIL') {
          Toast({
            context: this,
            selector: '#t-toast',
            message: '支付失败',
            duration: 2000,
            icon: 'close-circle',
          });
          setTimeout(() => {
            wx.redirectTo({
              url: '/order/list'
            });
          });
        } else if (err.code === 'ILLEGAL_CONFIG_PARAM') {
          Toast({
            context: this,
            selector: '#t-toast',
            message: '支付失败，微信支付商户号设置有误，请商家重新检查支付设置。',
            duration: 2000,
            icon: 'close-circle',
          });
          setTimeout(() => {
            wx.redirectTo({
              url: '/order/list'
            });
          });
        } else {
          Toast({
            context: this,
            selector: '#t-toast',
            message: err.msg || '提交支付超时，请稍后重试',
            duration: 2000,
            icon: '',
          });
          setTimeout(() => {
            // 提交支付失败  返回购物车
            wx.navigateBack();
          }, 2000);
        }
      }, );

  },

  // 处理支付
  handlePay(data, settleDetailData) {
    const {
      channel,
      payInfo,
      tradeNo,
      interactId,
      transactionId
    } = data;
    const {
      totalAmount,
      totalPayAmount,
      couponInfo,
      deductFeeInfo
    } = settleDetailData;
    const payOrderInfo = {
      payInfo: payInfo,
      orderId: tradeNo,
      orderAmt: totalAmount,
      payAmt: totalPayAmount,
      totalDeliveryFee: settleDetailData.totalDeliveryFee,
      interactId: interactId,
      tradeNo: tradeNo,
      transactionId: transactionId,
      remark: this.data.storeInfoList[0].remark,
      vipPrice: this.data.vipPrice,
      couponInfo,
      deductFeeInfo
    };

    // ticket订单
    if (this.data.ticketOrder) {
      payOrderInfo.ticketInfo = {
        totalAmount: this.data.amount + this.data.gift,
        gift: this.data.gift,
        ticket: this.data.ticket
      }
    }

    // console.log(data, settleDetailData)
    let goodsList = []
    this.data.orderCardList[0].goodsList.forEach(ele => {
      goodsList.push({
        thumb: ele.thumb,
        title: ele.title,
        specs: ele.specs,
        price: ele.price,
        spuId: ele.spuId,
        num: ele.num
      })
    })
    // console.log(goodsList)
    payOrderInfo.goodsList = goodsList

    if (channel === 'wechat') {
      wechatPayOrder(payOrderInfo)
        .then((payRes) => {
          // console.log(payRes, couponInfo)
          this.updateUserLimit(couponInfo?.list)
        })
    }
  },

  updateCoupon(couponList) { // 减少优惠券存量（有数量限制的）
    if (!couponList?.length) return
    const source = couponList[0]?.source
    // console.log(source)
    if (!(source.num * 1 > 0)) return
    ds.cloudUpdate('coupons', source._id, {
      num: source.num * 1 - 1
    }, res => {
      // console.log(res)
    })
  },

  async updateUserLimit(couponList) { // 增加用户领用量（有领用限制的）
    if (!couponList?.length) return
    const source = couponList[0]?.source
    if (!source.limit) return
    const userRes = await new Promise(resolve => {
      ds.cloudGetByOpenid('users', res => {
        resolve(res)
      })
    })
    const user = userRes.result.data[0]
    const couponRecord = user.couponRecord || {}
    couponRecord[source._id] = couponRecord[source._id] || {
      num: 0
    }
    couponRecord[source._id].num = couponRecord[source._id].num * 1 + 1
    await new Promise(resolve => {
      ds.cloudUpdate('users', user._id, {
        couponRecord
      }, res => {
        resolve()
      })
    })
  },
  hide() {
    // 隐藏 popup
    this.setData({
      'settleDetailData.abnormalDeliveryGoodsList': [],
    });
  },
  onReceipt() {
    // 跳转 开发票
    const invoiceData = this.invoiceData || {};
    wx.navigateTo({
      url: `/pages/order/receipt/index?invoiceData=${JSON.stringify(
        invoiceData,
      )}`,
    });
  },
  onCoupons(e) { // 选择优惠券，参见 select-coupons 组件
    const {
      submitCouponList,
      currentStoreId,
      settleDetailData
    } = this.data;
    const {
      goodsRequestList
    } = this;
    const {
      selectedList
    } = e.detail;
    // console.log('select coupon', selectedList)
    // 计算优惠
    let totalCouponAmount = 0
    const setlectList = selectedList.map(ele => {
      totalCouponAmount += (ele.source.minus * 1)
      return ele
    })
    settleDetailData.totalCouponAmount = totalCouponAmount
    settleDetailData.totalPayAmount -= totalCouponAmount
    settleDetailData.couponInfo = {
      list: selectedList,
      amount: totalCouponAmount,
    }
    // console.log('coupon amount', totalCouponAmount)
    this.setData({
      submitCouponList: setlectList,
      settleDetailData,
      couponsShow: false
    })
    return
    const tempSubmitCouponList = submitCouponList.map((storeCoupon) => {
      return {
        couponList: storeCoupon.storeId === currentStoreId ?
          selectedList : storeCoupon.couponList,
      };
    });
    const resSubmitCouponList = this.handleCouponList(tempSubmitCouponList);
    //确定选择优惠券
    this.handleOptionsParams({
      goodsRequestList
    }, resSubmitCouponList);

  },
  onOpenCoupons(e) { // 打开优惠券
    const {
      settleDetailData
    } = this.data
    const {
      storeid
    } = e.currentTarget.dataset;

    const data = this.data.settleDetailData
    const goodsIds = data.storeGoodsList[0].skuDetailVos.map(ele => ele.spuId)
    settleDetailData.totalPayAmount += Number(settleDetailData.totalCouponAmount || 0)
    settleDetailData.totalCouponAmount = 0
    // console.log(this.data, storeid, goodsIds, settleDetailData)
    this.setData({
      couponsShow: true,
      currentStoreId: storeid,
      goodsIds,
      settleDetailData
    });
  },
  async onUseDeductFee() {
    const {
      user,
      settleDetailData
    } = this.data

    ui.loading()
    const feeInfo = await adv.calcDeductFee(user)
    ui.loading(false)
    // console.log(feeInfo)

    if (feeInfo.fee < 1) {
      ui.toast(false, '佣金金额不足￥1')
      return
    }
    if (settleDetailData.totalPayAmount < 1) {
      ui.toast(false, '小计金额太小')
      return
    }
    const maxUsage = Math.min(settleDetailData.totalPayAmount - 1, feeInfo.fee)
    if (!await ui.confirmx(`是否结算￥${feeInfo.fee.toFixed(2)}并用于支付？（最多可用￥${maxUsage.toFixed(2)}）`)) return

    ui.loading()
    const settleRes = await adv.settleDeductFee(user, feeInfo)
    ui.loading(false)
    ui.toast(settleRes.success)
    if (!settleRes.success) return

    settleDetailData.totalPayAmount = settleDetailData.totalPayAmount - maxUsage
    settleDetailData.deductFeeInfo = feeInfo
    this.setData({
      settleDetailData
    })
  },
  handleCouponList(storeCouponList) {
    return storeCouponList
    //处理门店优惠券   转换成接口需要
    if (!storeCouponList) return [];
    const resSubmitCouponList = [];
    storeCouponList.forEach((ele) => {
      resSubmitCouponList.push(...ele.couponList);
    });
    return resSubmitCouponList;
  },

  onGoodsNumChange(e) {
    const {
      detail: {
        value
      },
      currentTarget: {
        dataset: {
          goods
        },
      },
    } = e;
    const index = this.goodsRequestList.findIndex(
      ({
        storeId,
        spuId,
        skuId
      }) =>
      goods.storeId === storeId &&
      goods.spuId === spuId &&
      goods.skuId === skuId,
    );
    if (index >= 0) {
      // eslint-disable-next-line no-confusing-arrow
      const goodsRequestList = this.goodsRequestList.map((item, i) =>
        i === index ? {
          ...item,
          quantity: value
        } : item,
      );
      this.handleOptionsParams({
        goodsRequestList
      });
    }
  },

  onPopupChange() {
    this.setData({
      popupShow: !this.data.popupShow,
    });
  },
});